<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/9/17
 * Time: 9:45
 * YY: 294963672@qq.com
 */

namespace App\Models;


use Illuminate\Database\Eloquent\Model;

class Goods extends Model
{

    protected $table = 'goods';

    protected $fillable = [
        'name', 'price',
    ];

    /**
     * 获取列表
     *
     * @param array $validated
     * @return array
     */
    public static function getList(array $validated): array
    {
        $model = Goods::when($validated['name'] ?? null, function ($query) use ($validated) {
            return $query->where('name', 'like', '%' . $validated['name'] . '%');
        })
            ->when($validated['start_at'] ?? null, function ($query) use ($validated) {
                return $query->whereBetween('created_at', [$validated['start_at'], $validated['end_at']]);
            });

        $total = $model->count('id');

        $goods = $model->select(['id', 'name', 'price', 'created_at', 'updated_at'])
            ->orderBy($validated['sort'] ?? 'created_at', $validated['order'] === 'ascending' ? 'asc' : 'desc')
            ->offset(($validated['offset'] - 1) * $validated['limit'])
            ->limit($validated['limit'])
            ->get();

        return [
            'goods' => $goods,
            'total' => $total
        ];
    }

    public static function create(array $attributes)
    {
        return static::query()->create($attributes);
    }

    /**
     * 更新
     *
     * @param array $data
     * @return array
     */
    public static function updateSave(array $data): array
    {

        $goods = Goods::find($data['id']);
        unset($data['id']);

        return [
            'result' => $goods->update($data),
            'admin' => $goods
        ];
    }
}